forvalue y = 2001(1)2023 {
// Set the directory where your .dta files are located
local directory "$root\data\raw\Schlenker\rawDataByYear\year`y'"

// Change the working directory to the specified folder
cd "`directory'"

foreach s in 1 4 5 6 8 9 {
clear
// Create a list of all .dta files in the directory
local files: dir "`directory'" files "fips`s'*.dta"

// Split the list of files into individual file names
local filecount: word count `files'

// If there are no files, exit the program
if `filecount' == 0 {
    display "No .dta files found in the specified directory."
    exit
}

// Initialize a variable to keep track of the first file
local firstfile = 1

// Loop through the list of files to append them
foreach file of local files {
	local filename = subinstr("`file'", ".dta", "", .)
	if strlen("`filename'") == 8 {
		if (`firstfile' == 1)  {
			use "`file'", clear
			local firstfile = 0
		} 
		else {
			append using "`file'"
		}
	}
}
save "..\y`y'\state`s'.dta", replace
}

local statelist 10 11 12 13 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 45 46 47 48 49 50 51 53 54 55 56
foreach s of local statelist {
clear
// Create a list of all .dta files in the directory
local files: dir "`directory'" files "fips`s'*.dta"

// Split the list of files into individual file names
local filecount: word count `files'

// If there are no files, exit the program
if `filecount' == 0 {
    display "No .dta files found in the specified directory."
    exit
}

// Initialize a variable to keep track of the first file
local firstfile = 1

// Loop through the list of files to append them
foreach file of local files {
	local filename = subinstr("`file'", ".dta", "", .)
	if strlen("`filename'") == 9 {
		if (`firstfile' == 1)  {
			use "`file'", clear
			local firstfile = 0
		} 
		else {
			append using "`file'"
		}
	}
}
save "..\y`y'\state`s'.dta", replace
}
}